import React, { useState, useEffect } from 'react';
import { Card, Typography, Spin, Button, message, Tabs, Tag, Alert } from 'antd';
import { RobotOutlined, BulbOutlined, ReloadOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import './InvestmentRecommendation.css';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

function InvestmentRecommendation({ symbol }) {
  const [loading, setLoading] = useState(false);
  const [aiLoading, setAiLoading] = useState(false);
  const [recommendation, setRecommendation] = useState(null);
  const [aiResult, setAiResult] = useState('');
  const [activeTab, setActiveTab] = useState('basic');

  // API基础URL，避免开发服务器代理影响流式响应
  const API_BASE_URL = process.env.NODE_ENV === 'production'
    ? ''
    : 'http://localhost:5000';

  // 获取基础投资建议
  const fetchRecommendation = async () => {
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/stock/${symbol}/recommendation`);
      const data = await response.json();
      if (response.ok) {
        setRecommendation(data);
      } else {
        throw new Error(data.error || 'Failed to fetch recommendation');
      }
    } catch (error) {
      console.error('Error:', error);
      message.error('获取投资建议失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 获取AI深度分析
  const getAIAnalysis = async (prompt, analysisType = 'comprehensive') => {
    setAiLoading(true);
    setAiResult('');

    try {
      const response = await fetch(`${API_BASE_URL}/api/stock/${symbol}/ai-analysis-stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
          'Cache-Control': 'no-cache'
        },
        body: JSON.stringify({
          question: prompt,
          analysis_type: analysisType,
          conversation_history: []
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      let buffer = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;

        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6).trim();
            if (data === '[DONE]') {
              return;
            }
            if (data) {
              try {
                const parsed = JSON.parse(data);
                if (parsed.content) {
                  setAiResult(prev => prev + parsed.content);
                } else if (parsed.error) {
                  throw new Error(parsed.error);
                }
              } catch (e) {
                console.warn('Parse error:', e);
                if (typeof data === 'string' && data.includes('error')) {
                  throw new Error('Stream error: ' + data);
                }
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('Error:', error);
      setAiResult(`错误: ${error.message}`);
      message.error('AI分析失败: ' + error.message);
    } finally {
      setAiLoading(false);
    }
  };

  const handleAnalysis = (analysisType) => {
    const analysis = analysisTypes.find(a => a.key === analysisType);
    if (analysis) {
      getAIAnalysis(analysis.prompt, analysisType);
    }
  };

  const analysisTypes = [
    {
      key: 'comprehensive',
      title: '综合分析',
      icon: '📊',
      prompt: '请提供全面的投资价值分析，包括估值、财务、风险评估和投资建议。'
    },
    {
      key: 'valuation',
      title: '估值分析',
      icon: '💰',
      prompt: '请进行深入的估值分析，包括PE、PB、PEG、DCF等方法，评估股价合理性。'
    },
    {
      key: 'financial',
      title: '财务分析',
      icon: '📈',
      prompt: '请分析财务健康状况，包括盈利能力、成长性、偿债能力和现金流。'
    },
    {
      key: 'technical',
      title: '技术分析',
      icon: '📉',
      prompt: '请进行技术面分析，包括趋势、均线、技术指标和短期价格预测。'
    },
    {
      key: 'risk',
      title: '风险评估',
      icon: '⚠️',
      prompt: '请全面评估投资风险，包括系统性风险、非系统性风险和风险管理建议。'
    },
    {
      key: 'outlook',
      title: '前景展望',
      icon: '🔮',
      prompt: '请分析发展前景和长期投资价值，包括行业趋势、竞争优势和成长驱动因素。'
    }
  ];

  // 获取推荐类型的颜色
  const getRecommendationColor = (recommendation) => {
    switch (recommendation) {
      case '买入': return 'green';
      case '持有': return 'orange';
      case '卖出': return 'red';
      case '观望': return 'blue';
      default: return 'default';
    }
  };

  // 获取信心等级的颜色
  const getConfidenceColor = (confidence) => {
    switch (confidence) {
      case '高': return 'green';
      case '中等': return 'orange';
      case '低': return 'red';
      default: return 'default';
    }
  };

  // 组件加载时获取基础建议
  useEffect(() => {
    if (symbol) {
      fetchRecommendation();
    }
  }, [symbol]);

  return (
    <Card
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <BulbOutlined />
          <span>投资建议</span>
        </div>
      }
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane
          tab={
            <span>
              <BulbOutlined />
              基础分析
            </span>
          }
          key="basic"
        >
          <div style={{ marginBottom: 16 }}>
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchRecommendation}
              loading={loading}
              size="small"
            >
              刷新数据
            </Button>
          </div>

          {loading ? (
            <div style={{ textAlign: 'center', padding: 20 }}>
              <Spin size="large" />
              <p>正在获取投资建议...</p>
            </div>
          ) : recommendation ? (
            <div>
              {/* 投资建议 */}
              <div style={{ marginBottom: 24, textAlign: 'center' }}>
                <Tag color={getRecommendationColor(recommendation.recommendation)} style={{ fontSize: 24, padding: '8px 16px' }}>
                  {recommendation.recommendation}
                </Tag>
                <div style={{ marginTop: 8 }}>
                  <Text type="secondary">信心等级: </Text>
                  <Tag color={getConfidenceColor(recommendation.confidence)}>
                    {recommendation.confidence}
                  </Tag>
                </div>
                <div style={{ marginTop: 8 }}>
                  <Text type="secondary">综合评分: </Text>
                  <Text strong style={{ color: recommendation.score >= 75 ? '#52c41a' :
                                                  recommendation.score >= 60 ? '#faad14' :
                                                  recommendation.score >= 45 ? '#1890ff' : '#f5222d' }}>
                    {recommendation.score}/100
                  </Text>
                </div>
              </div>

              {/* 详细评分 */}
              {recommendation.detailed_scores && (
                <div style={{ marginBottom: 24 }}>
                  <Title level={5}>详细评分:</Title>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 12 }}>
                    {Object.entries(recommendation.detailed_scores).map(([category, score]) => (
                      <div key={category} style={{ textAlign: 'center', padding: '12px', border: '1px solid #d9d9d9', borderRadius: '6px' }}>
                        <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>{category}</div>
                        <div style={{ fontSize: '20px', fontWeight: 'bold', color: score >= 15 ? '#52c41a' : score >= 10 ? '#faad14' : '#f5222d' }}>
                          {score}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 分析信号 */}
              <div style={{ marginBottom: 24 }}>
                <Title level={5}>分析信号:</Title>
                <div style={{
                  display: 'flex',
                  flexWrap: 'wrap',
                  gap: 8,
                  alignContent: 'flex-start'
                }}>
                  {recommendation.signals.map((signal, index) => {
                    // 根据信号内容智能分配颜色
                    let color = 'blue';
                    if (signal.includes('低估') || signal.includes('优秀') || signal.includes('强劲') || signal.includes('高') || signal.includes('强')) {
                      color = 'green';
                    } else if (signal.includes('高估') || signal.includes('较低') || signal.includes('风险') || signal.includes('偏高')) {
                      color = 'orange';
                    } else if (signal.includes('低') || signal.includes('弱') || signal.includes('下跌')) {
                      color = 'red';
                    }

                    return (
                      <Tag
                        key={index}
                        color={color}
                        style={{
                          margin: 0,
                          fontSize: '12px',
                          lineHeight: '20px',
                          maxWidth: '100%',
                          height: 'auto',
                          padding: '4px 8px',
                          whiteSpace: 'normal'
                        }}
                      >
                        {signal}
                      </Tag>
                    );
                  })}
                </div>
              </div>

              {/* 技术面摘要 */}
              {recommendation.technical_summary && (
                <div style={{ marginBottom: 24 }}>
                  <Title level={5}>技术面分析:</Title>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: 8 }}>
                    <div>
                      <Text type="secondary">趋势:</Text>
                      <div>
                        <Tag color={recommendation.technical_summary.trend === 'BULLISH' ? 'green' :
                                  recommendation.technical_summary.trend === 'BEARISH' ? 'red' : 'blue'}>
                          {recommendation.technical_summary.trend}
                        </Tag>
                      </div>
                    </div>
                    {recommendation.technical_summary.rsi && (
                      <div>
                        <Text type="secondary">RSI:</Text>
                        <div style={{ fontWeight: 'bold' }}>
                          {recommendation.technical_summary.rsi.toFixed(1)}
                        </div>
                      </div>
                    )}
                    <div>
                      <Text type="secondary">价格位置:</Text>
                      <div style={{ fontWeight: 'bold' }}>
                        {recommendation.technical_summary.price_position}%
                      </div>
                    </div>
                    <div>
                      <Text type="secondary">波动率:</Text>
                      <div style={{ fontWeight: 'bold' }}>
                        {recommendation.technical_summary.volatility}%
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* 基本面摘要 */}
              {recommendation.fundamental_summary && (
                <div style={{ marginBottom: 24 }}>
                  <Title level={5}>基本面指标:</Title>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: 8 }}>
                    {recommendation.fundamental_summary.pe && (
                      <div>
                        <Text type="secondary">PE:</Text>
                        <div style={{ fontWeight: 'bold' }}>{recommendation.fundamental_summary.pe}</div>
                      </div>
                    )}
                    {recommendation.fundamental_summary.pb && (
                      <div>
                        <Text type="secondary">PB:</Text>
                        <div style={{ fontWeight: 'bold' }}>{recommendation.fundamental_summary.pb}</div>
                      </div>
                    )}
                    {recommendation.fundamental_summary.roe && (
                      <div>
                        <Text type="secondary">ROE:</Text>
                        <div style={{ fontWeight: 'bold' }}>{recommendation.fundamental_summary.roe}%</div>
                      </div>
                    )}
                    {recommendation.fundamental_summary.dividend_yield && (
                      <div>
                        <Text type="secondary">股息率:</Text>
                        <div style={{ fontWeight: 'bold' }}>{recommendation.fundamental_summary.dividend_yield}%</div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 风险提示 */}
              <Alert
                message="风险提示"
                description={recommendation.warning}
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
              />

              {/* 更新时间 */}
              <Text type="secondary" style={{ fontSize: 12 }}>
                数据更新时间: {new Date(recommendation.last_updated).toLocaleString()}
              </Text>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: 20 }}>
              <Text type="secondary">暂无投资建议数据</Text>
            </div>
          )}
        </TabPane>

        <TabPane
          tab={
            <span>
              <RobotOutlined />
              AI深度分析
            </span>
          }
          key="ai"
        >
          {/* 分析类型选择 */}
          <div style={{ marginBottom: 16 }}>
            <Text strong>选择分析类型：</Text>
            <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12 }}>
              {analysisTypes.map((type) => (
                <Button
                  key={type.key}
                  type="default"
                  size="large"
                  className="analysis-button"
                  onClick={() => handleAnalysis(type.key)}
                  loading={aiLoading}
                  disabled={aiLoading}
                  style={{
                    height: 'auto',
                    padding: '16px 12px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: 8
                  }}
                >
                  <div style={{ fontSize: 24 }}>{type.icon}</div>
                  <div style={{ fontSize: 14, fontWeight: 'bold' }}>{type.title}</div>
                </Button>
              ))}
            </div>
          </div>

          {aiLoading && (
            <div style={{ textAlign: 'center', padding: 30 }}>
              <div style={{ marginBottom: 16 }}>
                <div className="loading-spinner" />
              </div>
              <p style={{ color: '#666', fontSize: 16, fontWeight: 500 }}>
                AI正在深度分析中...
              </p>
              <p style={{ color: '#999', fontSize: 12, marginTop: 8 }}>
                这可能需要10-30秒，请耐心等待
              </p>
            </div>
          )}

          {aiResult && (
            <div
              className="analysis-result"
              style={{
                padding: 20,
                backgroundColor: '#fafafa',
                borderRadius: 8,
                border: '1px solid #e8e8e8',
                fontSize: 14,
                lineHeight: 1.7,
                maxHeight: 600,
                overflowY: 'auto'
              }}
            >
  
              <div className="markdown-content">
                <ReactMarkdown
                  remarkPlugins={[remarkGfm]}
                  components={{
                    h1: ({node, ...props}) => <h1 {...props} />,
                    h2: ({node, ...props}) => <h2 {...props} />,
                    h3: ({node, ...props}) => <h3 {...props} />,
                    h4: ({node, ...props}) => <h4 {...props} />,
                    h5: ({node, ...props}) => <h5 {...props} />,
                    h6: ({node, ...props}) => <h6 {...props} />,
                    strong: ({node, ...props}) => <strong {...props} />,
                    em: ({node, ...props}) => <em {...props} />,
                    p: ({node, ...props}) => <p {...props} />,
                    ul: ({node, ...props}) => <ul {...props} />,
                    ol: ({node, ...props}) => <ol {...props} />,
                    li: ({node, ...props}) => <li {...props} />,
                    code: ({node, inline, ...props}) => inline ?
                      <code {...props} /> :
                      <code {...props} />,
                    pre: ({node, ...props}) => <pre {...props} />,
                    blockquote: ({node, ...props}) => <blockquote {...props} />,
                    table: ({node, ...props}) => <table {...props} />,
                    thead: ({node, ...props}) => <thead {...props} />,
                    tbody: ({node, ...props}) => <tbody {...props} />,
                    tr: ({node, ...props}) => <tr {...props} />,
                    th: ({node, ...props}) => <th {...props} />,
                    td: ({node, ...props}) => <td {...props} />
                  }}
                >
                  {(() => {
                    // 检查是否整个内容被包装在markdown代码块中
                    if (aiResult.includes('```markdown') && aiResult.includes('```')) {
                      // 提取markdown代码块中的内容
                      const match = aiResult.match(/```markdown\n([\s\S]*?)\n```/);
                      if (match) {
                        return match[1];
                      }
                    }
                    return aiResult;
                  })()}
                </ReactMarkdown>
              </div>
            </div>
          )}
        </TabPane>
      </Tabs>
    </Card>
  );
}

export default InvestmentRecommendation;